//! @Author: DengLibin
//! @Date: Create in 2023-11-07 09:13:58
//! @Description: 认证校验中间件

use axum::{
    body::Body,
    http::{Request, StatusCode},
    middleware::Next,
    response::Response,
};
use log::debug;
/// @Author: DengLibin
/// @Date: Create in 2023-11-07 10:15:55
/// @Description:
pub async fn auth(
    // run the `TypedHeader` extractor
    // auth: TypedHeader<Authorization<Bearer>>, //token校验 请求头格式: authorization: Bearer sfa23234234sdfsf
    // you can also add more extractors here but the last
    // extractor must implement `FromRequest` which
    // `Request` does
    request: Request<Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    debug!("-------------------------->middleware:auth start");
    if token_is_valid(&request) {
        let response = next.run(request).await;
        debug!("-------------------------->middleware:auth end");
        Ok(response)
    } else {
        Err(StatusCode::UNAUTHORIZED)
    }
}

/// @Author: DengLibin
/// @Date: Create in 2023-11-07 10:15:33
/// @Description: 验证token
fn token_is_valid<B>(request: &Request<B>) -> bool {
    let token_o = request.headers().get("token");
    if let Some(token) = token_o {
        if let Ok(s) = token.to_str() {
            debug!("token:{}", s);
            if s == "123456" {
                return true;
            }
        }
    }
    true
}
